<script lang="ts" setup>
import { Component, RendererElement, RendererNode, VNode, computed, watch, ref } from 'vue'
import { Handle } from '@vue-flow/core'
import { ArgumentItem } from '@/types/argument'

interface Props {
  label: string | object | VNode<RendererNode, RendererElement, {
    [key: string]: Any;
  }> | Component | undefined,
  id: string,
  inputs: (ArgumentItem & { active: boolean })[],
  outputs: (ArgumentItem & { active: boolean, data: Any })[],
  selected?: boolean,
  script: string
}
const props = defineProps<Props>()
const emit = defineEmits(['remove'])

const hiddenInpuRef = ref<HTMLInputElement>()

watch(() => props.selected, () => {
  if (props.selected) {
    hiddenInpuRef.value?.focus()
  }
})

const handlesInputs = computed(() => props.inputs.map((v, i) => ({
  id: v.name,
  position: 'left',
  type: 'target',
  label: v.name,
  offset: i,
  active: v.active
} as Any)))
const handlesOutputs = computed(() => props.outputs.map((v, i) => ({
  id: v.name,
  position: 'right',
  type: 'source',
  label: v.name,
  offset: i,
  active: v.active,
  data: v.data
} as Any)))
const maxHandles = computed(() => Math.max(handlesInputs.value.length, handlesOutputs.value.length, 1))

function onKeyUp (evt: KeyboardEvent) {
  if (evt.code !== 'Delete') {
    return
  }
  emit('remove')
}

defineExpose({
  get code () {
    return `def fn_${props.id}(${props.inputs.map(v => v.name).join(',')}):\n\t${props.script.split('\n').join('\n\t')}`
  },
  focus () {
    hiddenInpuRef.value?.focus()
  },
  async run (args: Any) {
    console.log(args, props.script)
    // const defines = []
    // for (const key in args) {
    //   defines.push(`${key}=${args.value}`)
    // }
    // const script = `${args}\n${props.script}`
    // const d = await invoke('run', { args, script })
    // const res = {} as Any
    // props.outputs.forEach(v => {
    //   res[v.name] = {
    //     type: v.type,
    //     value: ''
    //   }
    // })
    // return res
  }
})
</script>

<template>
  <div class="flow-node">
    <div class="header">
      <span class="label">{{ label }}</span>
    </div>
    <div class="workspace" :style="{ '--lines': maxHandles + 1 }">
    </div>
    <!-- 输入参数 -->
    <Handle v-for="item of handlesInputs" :id="item.id" :key="item.type" :position="item.position" :connectable="1"
      :style="{ '--offset': item.offset }" :class="{active: item.active}">
      <span class="handle-label">{{ item.label }}</span>
    </Handle>
    <!-- 输出参数 -->
    <Handle v-for="item of handlesOutputs" :id="item.id" :key="item.type" :position="item.position" :connectable-end="false"
      :style="{ '--offset': item.offset }" :class="{active: item.active}">
      <span class="handle-label" :class="{active: !!item.data}">
        {{ item.label }}
        <div class="data-viewer" v-if="item.data">{{ item.data }}</div>
      </span>
    </Handle>
    <input ref="hiddenInpuRef" type="text" autofocus="true" @keyup="onKeyUp" />
  </div>
</template>

<style lang="less" scoped>
.flow-node {
  padding: 0;
  --border-color: #445961;
  border: 1px solid var(--border-color);
  border-top-color: #445961;
  font-size: 12px;
  background: #303c3f;
  border-bottom-left-radius: 3px;
  border-bottom-right-radius: 3px;

  .header {
    background: #303c3f;
    padding: 5px 8px;
    display: flex;
    align-items: center;
    border-top: 1px solid var(--border-color);
    border-left: 1px solid var(--border-color);
    border-right: 1px solid var(--border-color);
    border-top-left-radius: 3px;
    border-top-right-radius: 3px;
    position: absolute;
    bottom: 100%;
    left: 0;
    right: 0;

    .label {
      white-space: nowrap;
      text-overflow: ellipsis;
      overflow: hidden;
    }
  }

  .workspace {
    min-width: 120px;
    min-height: calc(var(--lines) * 18px);
    display: flex;
    align-items: center;
  }

  input {
    opacity: 0;
    position: absolute;
    left: -1000px;
  }
}

.vue-flow__handle {
  transition: all 0.175s 0.25s;
  width: 4px;
  height: 4px;
  top: 18px;
  display: flex;
  align-items: center;

  .handle-label {
    position: absolute;
    white-space: nowrap;
  }

  &.vue-flow__handle-left {
    transform: translate(-50%, calc(18px * var(--offset) - 50%));

    .handle-label {
      left: 12px;
    }

    &.active {
      background-color: #3F3;
    }
  }

  &.vue-flow__handle-right {
    transform: translate(50%, calc(18px * var(--offset) - 50%));

    .handle-label {
      right: 12px;
      &.active {
        color: #3FF;
      }
    }

    &.active {
      background-color: #3FF;
    }
  }

  &:hover {
    transition: all 0.175s 0s;
    border-color: var(--el-border-color);
    background-color: var(--el-color-primary);
  }
}
</style>
<style>
.vue-flow__node.vue-flow__node-script.selected .flow-node {
  --border-color: #63e2b7;
}
</style>
